//
//  LCCallNumberView.m
//  cloudCall
//
//  Created by zhang on 2021/11/1.
//

#import "LCCallNumberView.h"
#import "RippleHeaderView.h"
#import "QTBClientCallCore.h"
#import "PatientChangeAlertView.h"

@interface CallingClickView : UIView

@property (nonatomic, assign)CGFloat imageSize;
@property (nonatomic, strong)UIImageView *imageView;
@property (nonatomic, strong)UILabel *nameLabel;
-(void)addTarget:(id)target Action:(SEL)action;

@end


@implementation CallingClickView


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpUI];
    }
    return self;
}

-(void)setUpUI{
    self.imageView = [[UIImageView alloc] init];
    [self addSubview:self.imageView];
    self.nameLabel = [[UILabel alloc] init];
    self.nameLabel.textColor = [UIColor colorWithHexString:@"#FFFFFF"];
    self.nameLabel.font = [UIFont systemFontOfSize:14];
    [self addSubview: self.nameLabel];
    [ self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.bottom.offset(0);
    }];
}

-(void)setImageSize:(CGFloat)imageSize {
    _imageSize = imageSize;
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.size.mas_equalTo(CGSizeMake(imageSize, imageSize));
        make.top.offset(0);
    }];
}

-(void)addTarget:(id)target Action:(SEL)action{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];
    [self addGestureRecognizer:tap];
}

@end



@interface LCCallNumberView ()
/**头像*/
@property (nonatomic, strong)RippleHeaderView *headerView;
/**名称*/
@property (nonatomic, strong)UILabel *nameLabel;
@property (nonatomic, strong)UIView *bottomView;

/// 呼叫状态
@property (nonatomic, strong)UILabel *noteLabel;
/// 通话中
@property (nonatomic, strong)UIView *answerView;
@property (nonatomic, strong)UILabel *answerTimeLabel;

/// 操作
@property (nonatomic, strong)UIView *handleView;

/// 挂断蒙板
@property (nonatomic, strong)UIView *maskView;

/// 切换患者
@property (nonatomic, strong)UIButton *changeBtn;

/**挂断*/
@property (nonatomic, strong)CallingClickView *hangupBtn;
/**麦克风*/
@property (nonatomic, strong)CallingClickView *voiceBtn;
/**接听*/
@property (nonatomic, strong)CallingClickView *answerBtn;
/**免提*/
@property (nonatomic, strong)CallingClickView *handsfreeBtn;

@property (nonatomic, strong)LCPatientModel *currentPatient;

@end


@implementation LCCallNumberView


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpUI];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callingTimeChange:) name:CallingTimeChangedNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getPatientsInfo:) name:GetPatientsInfoNotification object:nil];
        if ([WWPortManagerTool defaultTool].patientsArray && [WWPortManagerTool defaultTool].patientsArray.count) {
            LCPatientModel *model = [WWPortManagerTool defaultTool].patientsArray[0];
            self.currentPatient = model;
            self.changeBtn.hidden = !([WWPortManagerTool defaultTool].patientsArray.count > 1);
        }
    }
    return self;
}


-(void)setUpUI{
    self.backgroundColor = [UIColor colorWithHexString:@"#191919"];
    UIButton *closeButton = [[UIButton alloc] init];
    [self addSubview:closeButton];
    [closeButton addTarget:self action:@selector(closeAction) forControlEvents:(UIControlEventTouchUpInside)];
    [closeButton setImage:[UIImage imageNamed:@"ImageSource.bundle/call_shrink@3x"] forState:(UIControlStateNormal)];
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.top.offset(AutoStateHeight);
        make.size.mas_equalTo(CGSizeMake(64, 64));
    }];
    self.changeBtn = [[UIButton alloc] init];
    [self addSubview:self.changeBtn];
    self.changeBtn.hidden = YES;
    [self.changeBtn setTitle:@"切换客户" forState:(UIControlStateNormal)];
    self.changeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.changeBtn addTarget:self action:@selector(changeAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.changeBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [self.changeBtn setImage:[UIImage imageNamed:@"ImageSource.bundle/change_patients@3x"] forState:(UIControlStateNormal)];
    [self.changeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(closeButton.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(100, 40));
        make.right.offset(-10);
    }];
    
    self.headerView = [[RippleHeaderView alloc] initWithFrame:CGRectMake((kScreenWidth-112)/2, 120+AutoStateHeight, 112, 112)];
    [self addSubview:self.headerView];
    self.nameLabel = [[UILabel alloc] init];
    self.nameLabel.textColor = [UIColor colorWithHexString:@"#FFFFFF"];
    self.nameLabel.font = [UIFont systemFontOfSize:24 weight:(UIFontWeightMedium)];
    [self addSubview: self.nameLabel];
    self.nameLabel.text = [QTBClientCallCore shareCallCore].currentCall.identifier;
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.offset(276+AutoStateHeight);
    }];
    UIView *bottomView = [[UIView alloc] init];
    [self addSubview:bottomView];
    self.bottomView = bottomView;
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.offset(-AutoBottomHeight);
        make.height.mas_equalTo(150);
    }];
    self.handleView = [[UIView alloc] init];
    [self addSubview:self.handleView];
    [self.handleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.mas_equalTo(self.nameLabel.mas_bottom).offset(23);
        make.height.mas_equalTo(65);
    }];
    NSPredicate *dupObjPredicate;
    if (![QTBClientCallCore shareCallCore].currentCall.outbound) {
        if ([WWPortManagerTool defaultTool].isRequest) {
            dupObjPredicate = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind) {
                LCPatientActionModel *newObj = (LCPatientActionModel*)obj;
                BOOL isShow = (newObj.type == 0 ||  newObj.type == 1);
                if ([newObj.eventData[@"name"] isEqualToString:@"creatPatient"]) {
                    isShow = ![WWPortManagerTool defaultTool].patientsArray.count;
                }
                if ([newObj.eventData[@"name"] isEqualToString:@"patientDetail"]) {
                    isShow = [WWPortManagerTool defaultTool].patientsArray.count;
                }
                return isShow;
            }];
        } else {
            dupObjPredicate = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind) {
                return NO;
            }];
        }
    } else {
        dupObjPredicate = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind) {
            LCPatientActionModel *newObj = (LCPatientActionModel*)obj;
            BOOL isShow = (newObj.type == 0 ||  newObj.type == 2);
            if ([newObj.eventData[@"name"] isEqualToString:@"creatPatient"]) {
                isShow = ![WWPortManagerTool defaultTool].patientsArray.count;
            }
            if ([newObj.eventData[@"name"] isEqualToString:@"patientDetail"]) {
                isShow = [WWPortManagerTool defaultTool].patientsArray.count;
            }
            return isShow;
        }];
    }
    NSArray *actions = [[WWPortManagerTool defaultTool].actionArray filteredArrayUsingPredicate:dupObjPredicate];
    if (actions.count) {
        for (int i = 0; i < actions.count ; i++) {
            LCPatientActionModel *item = actions[i];
            CallingClickView *view = [[CallingClickView alloc] init];
            if (item.iconUrl) {
                [view.imageView sd_setImageWithURL:[NSURL URLWithString:item.iconUrl]];
            }
            view.nameLabel.text = item.name;
            view.imageSize = 42;
            view.tag = 100 + i;
            [self.handleView addSubview:view];
            [view addTarget:self Action:@selector(clickAction:)];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.top.offset(0);
                make.width.mas_equalTo(kScreenWidth/5);
                if (i == 0) {
                    make.left.offset(0);
                } else {
                    UIView *lastView = [self.handleView viewWithTag:99+i];
                    make.left.equalTo(lastView.mas_right);
                }
                if (i == actions.count-1) {
                    make.right.offset(0);
                }
            }];
        }
    }
    
    self.noteLabel = [[UILabel alloc] init];
    self.noteLabel.textColor = [UIColor colorWithHexString:@"#FFFFFF" withAlpha:0.7];
    self.noteLabel.font = [UIFont systemFontOfSize:14];
    [self addSubview: self.noteLabel];
    self.noteLabel.hidden = YES;
    [self.noteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.bottom.equalTo(bottomView.mas_top).offset(-56);
    }];
    self.answerView = [[UIView alloc] init];
    self.answerView.hidden = YES;
    [self addSubview: self.answerView];
    [self.answerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.bottom.equalTo(bottomView.mas_top).offset(-56);
    }];
    UIImageView *iconImageView = [[UIImageView alloc] init];
    iconImageView.image = [UIImage imageNamed:@"ImageSource.bundle/connecting@3x"];
    [self.answerView addSubview:iconImageView];
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.offset(0);
        make.size.mas_equalTo(CGSizeMake(16, 16));
    }];
    self.answerTimeLabel = [[UILabel alloc] init];
    self.answerTimeLabel.textColor = [UIColor colorWithHexString:@"#52C41A"];
    self.answerTimeLabel.font = [UIFont systemFontOfSize:14];
    [self.answerView addSubview: self.answerTimeLabel];
    [self.answerTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.right.offset(0);
        make.left.equalTo(iconImageView.mas_right).offset(4);
    }];
    self.hangupBtn = [[CallingClickView alloc] init];
    self.hangupBtn.imageView.image = [UIImage imageNamed:@"ImageSource.bundle/hangup@3x"];
    self.hangupBtn.nameLabel.text = @"挂断";
    self.hangupBtn.imageSize = 60;
    [self.hangupBtn addTarget:self Action:@selector(hangupAction)];
    self.voiceBtn = [[CallingClickView alloc] init];
    self.voiceBtn.imageView.image = [UIImage imageNamed:@"ImageSource.bundle/microphone_open@3x"];
    self.voiceBtn.nameLabel.text = @"关闭麦克风";
    self.voiceBtn.imageSize = 52;
    [self.voiceBtn addTarget:self Action:@selector(voiceAction)];
    self.answerBtn = [[CallingClickView alloc] init];
    self.answerBtn.imageView.image = [UIImage imageNamed:@"ImageSource.bundle/calling@3x"];
    self.answerBtn.imageSize = 52;
    self.answerBtn.nameLabel.text = @"接听";
    [self.answerBtn addTarget:self Action:@selector(answerAction)];
    self.handsfreeBtn = [[CallingClickView alloc] init];
    self.handsfreeBtn.imageView.image = [UIImage imageNamed:@"ImageSource.bundle/voice_close@3x"];
    self.handsfreeBtn.nameLabel.text = @"开启免提";
    self.handsfreeBtn.imageSize = 60;
    [self.handsfreeBtn addTarget:self Action:@selector(handsfreeAction)];
    self.maskView = [[UIView alloc] init];
    [self addSubview:self.maskView];
    self.maskView.hidden = YES;
    self.maskView.backgroundColor = [UIColor colorWithHexString:@"#191919" withAlpha:0.5];
    [self.maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.equalTo(self.nameLabel.mas_bottom);
    }];
}

-(void)setCurrentPatient:(LCPatientModel *)currentPatient {
    _currentPatient = currentPatient;
    [self.headerView removeFromSuperview];
    self.headerView = [[RippleHeaderView alloc] initWithFrame:CGRectMake((kScreenWidth-112)/2, 120+AutoStateHeight, 112, 112)];
    self.headerView.model = currentPatient;
    [self addSubview:self.headerView];
    self.nameLabel.text = currentPatient.name;
    currentPatient.isSelected = YES;
    [[NSNotificationCenter defaultCenter] postNotificationName:SetCurrentPatientNotification object:currentPatient];
}

-(void)clickAction:(UITapGestureRecognizer *)sender{
    UIView *view = sender.view;
    NSInteger index = view.tag - 100;
    if (index >= 0) {
        NSPredicate *dupObjPredicate = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind) {
            LCPatientActionModel *newObj = (LCPatientActionModel*)obj;
            BOOL isShow = (newObj.type == 0 ||  newObj.type == 1);
            if ([newObj.eventData[@"name"] isEqualToString:@"creatPatient"]) {
                isShow = ![WWPortManagerTool defaultTool].patientsArray.count;
            }
            if ([newObj.eventData[@"name"] isEqualToString:@"patientDetail"]) {
                isShow = [WWPortManagerTool defaultTool].patientsArray.count;
            }
            return isShow;
        }];
        NSArray *actions = [[WWPortManagerTool defaultTool].actionArray filteredArrayUsingPredicate:dupObjPredicate];
        LCPatientActionModel *item = actions[index];
        if (self.shrinkBlock) {
            self.shrinkBlock();
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:NativeClickActionNotification object:item];
    }
}

-(void)changeAction{
    PatientChangeAlertView *alert = [[PatientChangeAlertView alloc] init];
    alert.dataArray = [WWPortManagerTool defaultTool].patientsArray;
    [alert showSelectedView];
    INBWeakSelf;
    alert.selectedBlock = ^(LCPatientModel * _Nonnull model) {
        INBStrongSelf;
        self.currentPatient = model;
    };
}

-(void)setCallingType:(LCCallingType)callingType {
    [self.bottomView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.voiceBtn removeFromSuperview];
    [self.hangupBtn removeFromSuperview];
    [self.answerBtn removeFromSuperview];
    [self.voiceBtn removeFromSuperview];
    self.answerView.hidden = YES;
    self.noteLabel.hidden = YES;
    if (callingType == AWAITING && ![QTBClientCallCore shareCallCore].currentCall.outbound) {
        UIView *contentView = [[UIView alloc] init];
        [self.bottomView addSubview:contentView];
        [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.offset(0);
        }];
        [contentView addSubview:self.hangupBtn];
        [self.hangupBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(70, 90));
            make.top.bottom.left.offset(0);
        }];
        [contentView addSubview:self.answerBtn];
        [self.answerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(70, 90));
            make.top.right.offset(0);
            make.left.equalTo(self.hangupBtn.mas_right).offset(76);
        }];
        _callingType = callingType;
        return;
    }
    UIView *contentView = [[UIView alloc] init];
    [self.bottomView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    [contentView addSubview:self.voiceBtn];
    [self.voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 86));
        make.left.bottom.offset(0);
    }];
    [contentView addSubview:self.hangupBtn];
    [self.hangupBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 90));
        make.bottom.equalTo(self.voiceBtn.mas_bottom);
        make.top.offset(0);
        make.left.equalTo(self.voiceBtn.mas_right).offset(30);
    }];
    [contentView addSubview:self.handsfreeBtn];
    [self.handsfreeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 86));
        make.bottom.equalTo(self.voiceBtn.mas_bottom);
        make.right.offset(0);
        make.left.equalTo(self.hangupBtn.mas_right).offset(30);
    }];
    if (callingType == AWAITING) {
        self.noteLabel.text = @"正在呼叫中…请稍等";
        self.noteLabel.hidden = NO;
    } else if (callingType == CONNECTING) {
        self.answerView.hidden = NO;
        NSDate *connectDate = [QTBClientCallCore shareCallCore].currentCall.mediaCreateTime;
        if (connectDate) {
            NSTimeInterval timeout = [[NSDate date] timeIntervalSinceDate:connectDate];
            int hours = (int)(timeout/3600);
            int minute = (int)(timeout-hours*3600)/60;
            int second = timeout-hours*3600-minute*60;
            NSString *time = [NSString stringWithFormat:@"%.2d:%.2d",minute,second];
            if (hours > 0) {
                time = [NSString stringWithFormat:@"%.2d:%@",hours,time];
            }
            self.answerTimeLabel.text = [NSString stringWithFormat:@"通话中 %@",time];
        }
    } else if (callingType == HANGUP) {
        self.noteLabel.hidden = NO;
        self.maskView.hidden = NO;
        if (_callingType == CONNECTING) {
            if ([QTBClientCallCore shareCallCore].currentCall.makeHangup) {
                self.noteLabel.text = @"已挂断";
            }else{
                self.noteLabel.text = @"对方已挂断";
            }
        } else {
            self.noteLabel.text = @"已取消呼叫";
        }
    }
    _callingType = callingType;
}

-(void)callingTimeChange:(NSNotification *)sender{
    if (sender.object && [sender.object isKindOfClass:[NSString class]]) {
        NSString *time = sender.object;
        self.answerTimeLabel.text = [NSString stringWithFormat:@"通话中 %@",time];
    }
}

-(void)getPatientsInfo:(NSNotification *)sender{
    if ([WWPortManagerTool defaultTool].patientsArray && [WWPortManagerTool defaultTool].patientsArray.count) {
        LCPatientModel *model = [WWPortManagerTool defaultTool].patientsArray[0];
        self.currentPatient = model;
        self.changeBtn.hidden = !([WWPortManagerTool defaultTool].patientsArray.count > 1);
    }
    if (![QTBClientCallCore shareCallCore].currentCall.outbound && [WWPortManagerTool defaultTool].isRequest) {
        [self.handleView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        NSPredicate *dupObjPredicate = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind) {
            LCPatientActionModel *newObj = (LCPatientActionModel*)obj;
            BOOL isShow = (newObj.type == 0 ||  newObj.type == 1);
            if ([newObj.eventData[@"name"] isEqualToString:@"creatPatient"]) {
                isShow = ![WWPortManagerTool defaultTool].patientsArray.count;
            }
            if ([newObj.eventData[@"name"] isEqualToString:@"patientDetail"]) {
                isShow = [WWPortManagerTool defaultTool].patientsArray.count;
            }
            return isShow;
        }];
        NSArray *actions = [[WWPortManagerTool defaultTool].actionArray filteredArrayUsingPredicate:dupObjPredicate];
        if (actions.count) {
            for (int i = 0; i < actions.count ; i++) {
                LCPatientActionModel *item = actions[i];
                CallingClickView *view = [[CallingClickView alloc] init];
                if (item.iconUrl) {
                    [view.imageView sd_setImageWithURL:[NSURL URLWithString:item.iconUrl]];
                }
                view.nameLabel.text = item.name;
                view.imageSize = 42;
                view.tag = 100 + i;
                [self.handleView addSubview:view];
                [view addTarget:self Action:@selector(clickAction:)];
                [view mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.bottom.top.offset(0);
                    make.width.mas_equalTo(kScreenWidth/5);
                    if (i == 0) {
                        make.left.offset(0);
                    } else {
                        UIView *lastView = [self.handleView viewWithTag:99+i];
                        make.left.equalTo(lastView.mas_right);
                    }
                    if (i == actions.count-1) {
                        make.right.offset(0);
                    }
                }];
            }
        }
    }
}

-(void)answerAction{
    if (self.answerBlock) {
        self.answerBlock();
    }
}

-(void)closeAction{
    if (self.shrinkBlock) {
        self.shrinkBlock();
    }
}

-(void)hangupAction{
    self.callingType = HANGUP;
    if (self.hangupBlock) {
        self.hangupBlock();
    }
}

-(void)voiceAction{
    NSString *name = self.voiceBtn.nameLabel.text;
    BOOL voice = [name isEqualToString:@"关闭麦克风"];
    if (voice) {
        self.voiceBtn.imageView.image = [UIImage imageNamed:@"ImageSource.bundle/microphone_close@3x"];
        self.voiceBtn.nameLabel.text = @"开启麦克风";
    } else {
        self.voiceBtn.imageView.image = [UIImage imageNamed:@"ImageSource.bundle/microphone_open@3x"];
        self.voiceBtn.nameLabel.text = @"关闭麦克风";
    }
    if (self.voiceBlock) {
        self.voiceBlock(voice);
    }
}

-(void)handsfreeAction{
    NSString *name = self.handsfreeBtn.nameLabel.text;
    BOOL handsfree = [name isEqualToString:@"开启免提"];
    if (handsfree) {
        self.handsfreeBtn.imageView.image = [UIImage imageNamed:@"ImageSource.bundle/voice_open@3x"];
        self.handsfreeBtn.nameLabel.text = @"取消免提";
    } else {
        self.handsfreeBtn.imageView.image = [UIImage imageNamed:@"ImageSource.bundle/voice_close@3x"];
        self.handsfreeBtn.nameLabel.text = @"开启免提";
    }
    if (self.handsfreeBlock) {
        self.handsfreeBlock(handsfree);
    }
}


-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end



